const {
deleteData,
page,
list,
newsData,
option,
} = require("../../api/index.js")
const utils = require("../../utils/index.js")
Page({
/**
* 页面的初始数据
*/
data: {

        questList: [],
    pageNum: 1,
    pageSize: 9999, // 一次性加载全部项目
    total: 0,
    flag: false, // 不再需要分页加载


popopShow:false,

xiangmujieduanOptions:[],
showToTopButton: true,
onPageScrollTop: 0, // 存储滚动距离的变量
goodsListData: [],
activeIndex: 0,
allData: [],
deleteShow: false,
className:"",
name:"",
addAuth:"",
delAuth: "",
editAuth:"" ,
userid:"",
baseURL: wx.getStorageSync('baseURL') + "/",
isAuthStatus:false,
latestProjects: [],
latestProjectsLoop: [], // 用于无缝滚动
previewProjects: [],
scrollLeft: 0, // 自动滚动用
autoScrollTimer: null, // 自动滚动定时器
projectItemWidth: 0, // 单个项目宽度
projectListWidth: 0, // 原始项目区总宽度
},

/**
* 生命周期函数--监听页面加载
*/
async onLoad(options) {
this.setData({
        isAuthStatus: wx.getStorageSync('isAuth'),
        userid:wx.getStorageSync('userid')
})
if(options?.userid) {
this.setData({
    userid:options.userid
})

}
const currentPageUrl = this.getCurrentPageUrl();
if(getApp().globalData.name!=null){
this.setData({
    name: getApp().globalData.name
})
getApp().globalData.name=null
this.searhandler()
}

 let obj = {};
this.setData({
        xiangmujieduanOptions : '萌创期,初创期,孵创期'.split(',')
})
this.setData({
    ...obj
})

},

onShow() {
// 获取当前页面栈
const pages = getCurrentPages();
// 获取当前页面对象
const currentPage = pages[pages.length - 1];
// 获取当前页面的显示报告对象
let displayReporter = currentPage.__displayReporter;
if (getApp().globalData.name == null) {
    this.setData({
        name: null
    })
    this.setData({
        isAuthStatus: wx.getStorageSync('isAuth')
    })
    }
const currentPageUrl = this.getCurrentPageUrl();
if(getApp().globalData.name){
    this.setData({
        name: getApp().globalData.name
    })
    getApp().globalData.name=null
    this.searhandler()
}
this.setData({pageNum:1,goodsListData:[]})
this.getData()

// 自动横向滚动
if (this.data.autoScrollTimer) clearInterval(this.data.autoScrollTimer);
let that = this;
setTimeout(function() {
  that.data.autoScrollTimer = setInterval(function() {
    let next = that.data.scrollLeft + 2;
    if (next >= that.data.projectListWidth) {
      // 到达原始内容宽度，瞬间重置scrollLeft为0
      that.setData({ scrollLeft: 0 });
      next = 2;
    }
    that.setData({ scrollLeft: next });
  }, 30);
}, 500);

},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onPageShow() {
// 页面显示时执行的操作
},

xiangmujieduanChange(e){
this.setData({
        xiangmujieduan: e.currentTarget.dataset.item
})
},





screenReset(){
    let obj={}
//xiangmujieduan
obj["xiangmujieduan"]=""
    this.setData(obj)

},



async   search(){
const nowTable=wx.getStorageSync('nowTable')
let searchForm = {
page: 1,
limit: 999,
 sfsh: "是"
}

searchForm["sort"]="tijiaoshijian";
searchForm["order"]="desc";

if(this.data.xiangmumingcheng){
    searchForm['xiangmumingcheng'] = '%' + this.data.xiangmumingcheng + '%'
}
if(this.data.xiangmujieduan){
    searchForm['xiangmujieduan'] ='%' +  this.data.xiangmujieduan + '%'
}

let user = wx.getStorageSync("userid")?wx.getStorageSync('userSession'):{};
let res = {};
if( this.data.isAuthStatus) {
   
res = await page(`xiangmuxinxi`, searchForm);
} else {
res = await list(`xiangmuxinxi`, searchForm);
}


let goodsListData
// 如果是第一页数据置空
 if ( this.data.pageNum == 1) {
     goodsListData = []
 };
if(res.code==0){
    goodsListData=res.data.list.map(item=>{
item.xiangmutupian.indexOf('http') !== -1?item.xiangmutupian: item.xiangmutupian = this.data.baseURL+item.xiangmutupian?.split(",")[0].replace('upload','flie')
        return item
    })
this.setData({
goodsListData: goodsListData,
popopShow:false
})
}



},
/**
* 生命周期函数--监听页面显示
*/
getCurrentPageUrl() {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const currentPageUrl = `/${currentPage.route}`;
return currentPageUrl;
},
async  handleTabClick(e) {
        let params={
         sfsh: "是"
        }
        const nowTable=  wx.getStorageSync('nowTable')
},
    async searhandler(){
        let token = wx.getStorageSync('token')
        if (!token) {
            return
        }
let targetName="xiangmumingcheng"
        const allData=this.data.allData

        let goodsListData

        if(this.data.name==''){
            goodsListData=allData
        }else{
            goodsListData = allData.filter(item => item[targetName].includes(this.data.name));

        }

        this.setData({
            goodsListData  : goodsListData        })



    },
screenBoxShow() {
this.setData({
    popopShow: true
})
},
addTap() {
getApp().globalData.detailId=null
wx.navigateTo({
url: `/pages/xiangmuxinxi/update-and-add`
})
if(this.data.isAuthStatus) {
setTimeout(function () {
    wx.setStorageSync('isAuth', true)
}, 1000)
}
},
searchListHandler(e) {
this.setData({
goodsListData: e.detail.data
})
},
onPageScroll(e) {
if (e.scrollTop >= 225) {
this.setData({
    showToTopButton: true
});
}

},
backToTop() {
wx.pageScrollTo({
scrollTop: 0, // 返回顶部的位置
duration: 1000, // 滚动动画的时长，单位为 ms
});
// 返回顶部时隐藏按钮

},
deleteBtn(e) {
wx.showModal({
title: '提示',
content: '确认删除？',
complete: async (res) => {
    if (res.cancel) {}
    if (res.confirm) {
        const id = e.currentTarget.dataset.id;
        const res = await deleteData("xiangmuxinxi",[id])
        console.log(res);
        if (res.code == 0) {
            this.onShow()
        }
    }
}
})
},
editBtn(e) {
const item = e.currentTarget.dataset.item;
if(item?.id){
getApp().globalData.detailList =item;
getApp().globalData.detailId=item.id;
wx.navigateTo({
url: `/pages/xiangmuxinxi/update-and-add?id=${item.id}&isAuth=${this.data.isAuthStatus}`
})
if(this.data.isAuthStatus) {
setTimeout(function () {
wx.setStorageSync('isAuth', true)
}, 1000)
}
}
},
async detailBtn(e) {
const item = e.currentTarget.dataset.item;
if(item?.id){
getApp().globalData.detailId = item.id;
getApp().globalData.detailList =item
wx.navigateTo({
url: `/pages/xiangmuxinxi/detail?isAuth=${this.data.isAuthStatus}`
})
if(this.data.isAuthStatus) {
setTimeout(function () {
wx.setStorageSync('isAuth', true)
}, 1000)
}
    }

},
     /**
      * 页面上拉触底事件的处理函数
      */
onReachBottom() {

         if (this.data.flag ) {
             this.setData({
                 flag: false
             })
             this.getData(); // 疯狂的请求的方法
         }
     },
/**
 * 加载更多按钮点击事件
 */
onLoadMoreTap() {
    if (this.data.flag) {
        this.setData({ flag: false });
        this.getData();
    }
},
async getData() {
    const obj={
        page: this.data.pageNum,
        limit: this.data.pageSize,
         sfsh: "是"
    }
const nowTable=wx.getStorageSync('nowTable')
const userId= getApp().globalData.userInfo.id
let isAuthObj={}
if(this.data.isAuthStatus){
//111 xiangmuxinxi Xiangmuxinxi xiangmuxinxi ${pathname}
console.log('Xiangmuxinxi  xiangmuxinxi')
isAuthObj['addAuth']   = utils.isAuth("xiangmuxinxi", "新增")
isAuthObj['delAuth']  = utils.isAuth("xiangmuxinxi", "删除")
isAuthObj['editAuth']   =utils.isAuth("xiangmuxinxi", "修改")
}else{
isAuthObj['addAuth']   = utils.isAuthFront("xiangmuxinxi", "新增")
isAuthObj['delAuth']  = utils.isAuthFront("xiangmuxinxi", "删除")
isAuthObj['editAuth']   =utils.isAuthFront("xiangmuxinxi", "修改")
}
//前后台权限判断
this.setData(isAuthObj)

    obj["sort"]="tijiaoshijian";
    obj["order"]="desc";


let resList
var that = this
obj['page']=this.data.pageNum;
obj['limit']=this.data.pageSize;
let user = wx.getStorageSync("userid")?wx.getStorageSync('userSession'):{};
    if(this.data.isAuthStatus){

        resList = await page("xiangmuxinxi",obj)
    }else{
         resList= await list("xiangmuxinxi",obj)
    }
let resultdata = [];
if(resList.code==0){
    let mylist = this.data.goodsListData;
        //先处理成你想要的数据 下面再去赋值
          let    resData =  resList.data.list.map(item => {
item.xiangmutupian?.indexOf('http') !== -1?item.xiangmutupian: item.xiangmutupian = this.data.baseURL+item.xiangmutupian?.split(",")[0].replace('upload','flie');
return item;
});
        if (that.data.pageNum == 1) {
            mylist = []
        }

        // 新旧数据合并到一起
        if(resList.data.list.length>0){
      resultdata = this.data.goodsListData.concat(resData)
        }
        if (this.data.pageNum<resList.data.totalPage ){
            that.setData({
                pageNum:obj.page+ 1,
                flag:true
            })
        } else {
            that.setData({
                flag:false
            })
        }
        that.setData({
            goodsListData:  resultdata ,
            questList: mylist,
            total: resList.total,
            allData: resultdata // 修正为完整数据
        })
        
    }


// 商品名称
if (getApp().globalData.name != null) {
this.setData({
goodsListData:  getApp().globalData.goodsList ,
})
getApp().globalData.name = null
console.log('页面重新加载');
}

if (resultdata && resultdata.length > 0) {
  // 按时间倒序
  let sorted = resultdata.slice().sort((a, b) => new Date(b.tijiaoshijian) - new Date(a.tijiaoshijian));
  // 拼接一份用于无缝滚动
  let loopList = sorted.slice(0, 4).concat(sorted.slice(0, 4));
  this.setData({
    latestProjects: sorted.slice(0, 4),
    latestProjectsLoop: loopList,
    previewProjects: sorted.slice(4, 14) // 预览区从第5个开始，最多10个
  });
  // 计算宽度
  const sys = wx.getSystemInfoSync();
  const itemWidth = sys.windowWidth * 0.6 + 20 * sys.windowWidth / 750; // 60vw+20rpx
  this.setData({
    projectItemWidth: itemWidth,
    projectListWidth: itemWidth * 4
  });
}

},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
    wx.removeStorageSync('isAuth');
    if (this.data.autoScrollTimer) clearInterval(this.data.autoScrollTimer);
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
    if (this.data.autoScrollTimer) clearInterval(this.data.autoScrollTimer);
},

/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {

},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {

},
onSearch: function(e) {
  const value = e.detail.value;
  this.setData({ name: value });
  if (typeof this.search === 'function') {
    this.search();
  }
},
onSearchBtn: function(e) {
  if (typeof this.search === 'function') {
    this.search();
  }
},
onInputChange: function(e) {
  this.setData({ name: e.detail.value });
},
onCancelSearch: function() {
  this.setData({ name: '' });
  this.searhandler();
},
async searhandler() {
  let targetName = "xiangmumingcheng";
  const allData = this.data.allData || [];
  const keyword = (this.data.name || '').trim().toLowerCase();
  let goodsListData;
  if (!keyword) {
    goodsListData = allData;
  } else {
    goodsListData = allData.filter(item => {
      const value = (item[targetName] || '').toLowerCase();
      return value.includes(keyword);
    });
  }
  this.setData({
    goodsListData: goodsListData
  });
},
})
